import { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import { MenuType } from "type/menu";
import { getAuthority } from './authority'
import _ from "lodash";
export const useQueryStr = (name: string) => {
  const location = useLocation();
  if (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    console.log("history", location);
    var r = location.search.substr(1).match(reg);
    if (r != null && r !== undefined) {
      return decodeURI(r[2]);
    }
    return null;
  } else {
    return location.pathname.split("/").pop();
  }
};

export const useDebounce = <T>(value: T, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);
  useEffect(() => {
    const timeout = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timeout);
  }, [value, delay]);
  return debouncedValue;
};

// 删除的时候，计算当前页面
export const getCurrent = (
  total: number,
  filter: { current: number; pageSize: number }
) => {
  let page = Math.ceil(total / filter.pageSize);
  if (filter.current > page) {
    return page === 0 ? 1 : page;
  } else {
    return filter.current;
  }
};

// 控制菜单权限
const user_auth = getAuthority()
export function checkAuth(list: MenuType[] = []) {
  let arr = _.cloneDeep(list);
  let array: MenuType[] = [];
  arr.forEach((item: MenuType) => {
    let obj: any = {};
    if (item.authority) {
      let result = false;
      if (item.authority.indexOf(user_auth) !== -1 || !user_auth) {
        result = true
      }
      // 权限通过继续判断
      if (result) {
        if (item.children) {
          obj = Object.assign({}, item);
          obj.children = checkAuth(item.children);
          array.push(obj);
        } else {
          array.push(item);
        }
      }
    } else {
      if (item.children) {
        obj = item;
        obj.children = checkAuth(item.children);
        array.push(obj);
      } else {
        array.push(item);
      }
    }
  });
  console.log(array)
  return array;
}


// 下载文件
export const downUrl = (res: any) => {
  let objectURL = window.URL.createObjectURL(res.data);
  const a = window.document.createElement('a');
  a.href = objectURL;
  a.download = res.fileName;
  a.click();
  a.remove();
  // 释放创建的url对象
  window.URL.revokeObjectURL(objectURL);
};